<?php

namespace app\model\goods;

use app\base\BaseModel;
use app\libs\Util;
use app\model\activity\ActivityGoodsModel;
use app\model\agency\AgencyGoodsModel;
use app\model\order\OrderItemModel;
use app\model\user\UserCartModel;
use app\model\user\UserCollectUpModel;
use app\model\user\UserModel;
use think\facade\Db;
use think\Image;
use think\model\concern\SoftDelete;

/**
 *
 * 模型-goods
 * Class GoodsModel
 * @package app\model
 */
class GoodsModel extends BaseModel
{
    use SoftDelete;

    protected $name = 'goods';
    protected $store_id = 0;

    /**
     * 店铺id 查询范围
     * @param $query
     * @param $store_id
     */
    public function scopeStoreId($query, $store_id)
    {
        if (!empty($store_id)) {
            $query->where('store_id', $store_id);
        }
    }

    /**
     * 限制会员
     * @param $query
     * @param $is_member
     */
    public function scopeIsMember($query, $is_member)
    {
        if (!empty($is_member)) {
            $query->where('is_member', '<=', $is_member);
        }
    }

    /**
     * 范围查询-status
     * @param $query
     * @param $status
     */
    public function scopeStatus($query, $status)
    {
        if (!empty($status)) {
            if (intval($status) == 5) {
                $query->where('a.goods_status', '>', 2);
            } else {
                $query->where('a.goods_status', '=', $status);
            }

        }
    }

    /**
     * 范围查询-keyword
     * @param $query
     * @param $keyword
     */
    public function scopeKeyword($query, $keyword)
    {
        if (!empty($keyword)) {
            $query->whereLike('a.goods_title', "%$keyword%");
        }
    }


    # 分类查询
    public function scopeGoodsType($query, $goodsType = '')
    {
        if (!empty($goodsType)) {
            if (is_array($goodsType)) {
                $query->whereIn('a.goods_type_id', $goodsType);
            } else {
                $query->where('a.goods_type_id', $goodsType);
            }
        }
    }

    public function scopeWhereid($query, $ids = '')
    {
        if (!empty($ids)) {
            $query->whereIn('a.id', $ids);
        }
    }

    # 分页列表 商品统计 2020-07-09
    public function getGoodsData($keyword, $timeStr, $current_page, $list_rows, $field, $order, $store_id = 0)
    {
        $map_order = [];
        if (is_array($timeStr)) {
            $map_order[] = ['a.create_time', 'BETWEEN TIME', [$timeStr[0], $timeStr[1] . " 23:59:59"]];
        } else {
            # 查询今天
            if ($timeStr == 1) {
                $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                $map_order[] = ['a.create_time', 'between', "$beginToday,$endToday"];
            }
            # 查询本周
            if ($timeStr == 2) {
                $beginWeek = mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y"));
                $endWeek = mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y"));
                $map_order[] = ['a.create_time', 'BETWEEN TIME', [$beginWeek, $endWeek]];
            }
            # 查询本月
            if ($timeStr == 3) {
                $beginThismonth = mktime(0, 0, 0, date('m'), 1, date('Y'));
                $endThismonth = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
                $map_order[] = ['a.create_time', 'BETWEEN TIME', [$beginThismonth, $endThismonth]];
            }
            # 查询上月
            if ($timeStr == 4) {
                $begin_time = date('Y-m-01 00:00:00', strtotime('-1 month'));
                $end_time = date("Y-m-d 23:59:59", strtotime(-date('d') . 'day'));
                $map_order[] = ['a.create_time', 'BETWEEN TIME', [$begin_time, $end_time]];
            }
            # 查询今年
            if ($timeStr == 5) {
                $begin_year = strtotime(date("Y", time()) . "-1" . "-1"); //本年开始
                $end_year = strtotime(date("Y", time()) . "-12" . "-31"); //本年结束
                $map_order[] = ['a.create_time', 'BETWEEN TIME', [$begin_year, $end_year]];
            }
            # 查询去年
            if ($timeStr == 6) {
                $old = date("Y", time()) - 1;
                $begin_year = strtotime($old . "-1" . "-1"); //本年开始
                $end_year = strtotime($old . "-12" . "-31"); //本年结束
                $map_order[] = ['a.create_time', 'BETWEEN TIME', [$begin_year, $end_year]];
            }
        }
        $order_str = $field . " " . $order;
        $order_model = new OrderItemModel();
        if (!empty($store_id)) {
            $map_order['b.store_id'] = $store_id;
        }
        $order_model = $order_model->alias('a')
            ->leftJoin("t_goods b", "a.goods_id=b.id")
            ->field('b.store_id as store_id,b.id,b.goods_title,b.goods_img,b.goods_storage,count(a.order_id) as order_num,sum(a.goods_number) as order_sales_num, sum(a.order_total) as order_price,sum(a.goods_price)-sum(a.cost_price) as order_profit')
            ->group('a.goods_id')
            ->where($map_order)
            ->where('a.order_status', '>', 1)
            ->order($order_str);
        if (!empty($keyword)) {
            $order_model->whereLike('b.goods_title', '%' . $keyword . "%");
        }
        $dataList = $order_model->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
//        $dataList = $this->alias('a')
//            ->leftJoin("t_order_item b", "a.id=b.goods_id")
//            ->keyword($keyword)
//            ->field('a.id,a.goods_title,a.goods_img,a.goods_storage,sum(b.goods_number) as order_sales_num, sum(b.order_total) as order_price,sum(b.top_money) as order_profit')
//            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $order_model = new OrderItemModel();
        $goods_number = $order_model->alias('a')
            ->where($map_order)
            ->where('a.order_status', '>', 1)
            ->sum('goods_number');
        foreach ($dataList as $key => $value) {
            $dataList[$key]['order_sales_num_per'] = round(intval($value['order_sales_num']) / intval($goods_number) * 100, 2);
        }
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
        return $ret;
    }

    /**
     * 获取分页列表
     * @param $goodsType
     * @param $status
     * @param $keyword
     * @param $current_page
     * @param $list_rows
     * @param string $field
     * @param array $goods_ids
     * @param int $goods_storage
     * @param int $store_id
     * @return array
     */
    public function getPageData($goodsType, $status, $keyword, $current_page, $list_rows, $field = 'a.*', $goods_ids = [], $goods_storage = 0, $store_id = 0)
    {
        $model = $this->alias("a")
            ->leftJoin("t_goods_type b", "a.goods_type_id=b.id")
            ->storeId($store_id)
            ->field($field)
            ->status($status)
            ->keyword($keyword)
            ->goodsType($goodsType)
            ->order('a.sort', 'desc')
            ->order('a.id', 'desc');
        if (!empty($goods_ids)) {
            $model = $model->whereNotIn('a.id', implode(',', $goods_ids))->where('goods_storage', '>=', $goods_storage);
        }
        $dataList = $model->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
        return $ret;
    }

    /**
     * 获取商品列表
     * @param $map
     * @param $keyword
     * @param $current_page
     * @param $list_rows
     * @param string $field
     * @return array
     */
    public function getPageDataList($map, $keyword, $current_page, $list_rows, $field = 'a.*')
    {
        $model = $this->alias("a")
            ->where('a.goods_storage', '>', 0)
            ->field($field)
            ->where($map)
            ->keyword($keyword)
            ->order('a.sort', 'desc')
            ->order('a.id', 'desc');
        $dataList = $model->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
        return $ret;
    }

    /**
     * 获取列表数据
     * @param $map
     * @param $order
     * @param $limit
     * @param string $field
     * @param int $store_id
     * @param int $is_member
     * @return array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getListIn($map, $order, $limit, $field = '*', $store_id = 0, $is_member = 1)
    {
        if (isset($map['whereIn'])) {
            $key = $map['whereIn']['field'];
            $condition = $map['whereIn']['condition'];
            unset($map['whereIn']);
            $list = $this->storeId($store_id)
                ->isMember($is_member)
                ->whereIn($key, $condition . "")
                ->where($map)->order($order)
                ->limit($limit)->field($field)->select();
        } else {
            $list = $this->storeId($this->store_id)
                ->isMember($is_member)
                ->where($map)->order($order)
                ->limit($limit)->field($field)->select();
        }
        return $list;
    }

    /**
     * 获取列表数据
     * @param $map
     * @param $order
     * @param $limit
     * @param string $field
     * @param int $store_id
     * @param int $user_id
     * @param int $is_member
     * @return array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getListCommonIn($map, $order, $limit, $field = '*', $store_id = 0, $user_id = 0, $is_member = 1)
    {
        if (isset($map['whereIn'])) {
            $key = $map['whereIn']['field'];
            $condition = $map['whereIn']['condition'];
            unset($map['whereIn']);
            $list = $this->storeId($store_id)
                ->isMember($is_member)
                ->whereIn($key, $condition . "")
                ->where($map)->order($order)
                ->limit($limit)->field($field)->select();
        } else {
            $list = $this->storeId($this->store_id)
                ->isMember($is_member)
                ->where($map)->order($order)
                ->limit($limit)->field($field)->select();
        }

        if (empty($list)) {
            return [];
        }
        foreach ($list as $index => &$value) {
            $goods_common_model = new GoodsCommonModel();
            $goods_common_list = $goods_common_model->getCommonGoodsUserid($value['id'], [], $user_id, true);
            $value['goods_common_list'] = $goods_common_list;
            if (count($goods_common_list) > 1) {
                $value['attr_show'] = false;
            } else {
                $value['attr_show'] = true;
            }
        }
        return $list;
    }

    /**
     * 获取商品列表（商品id集合）
     * @param string $goods_ids
     * @param string $field
     * @param int $store_id
     * @return array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGoodsIdIn($goods_ids = '', $field = '*', $store_id = 0)
    {
        $goods_list = $this->storeId($store_id)->whereIn('id', $goods_ids)->field($field)->select();
        if (empty($goods_list)) {
            return [];
        }
        return $goods_list;
    }

    /**
     * 搜索商品
     * @param $formData
     * @param string $field
     * @param int $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function goodsSearch($formData, $field = "a.store_id,a.goods_type_id,a.goods_title,a.goods_text,a.goods_img,a.goods_max_price,a.goods_min_price,a.goods_min_market_price,a.id as goods_id")
    {
        $keyword = isset($formData['keyword']) ? $formData['keyword'] : "";
        if (!empty($keyword)) {
            HotKeywordModel::addSearchCount($keyword);
        }
        $goodsType = isset($formData['goodsType']) ? $formData['goodsType'] : 0;
        $pagenow = isset($formData['pagenow']) ? $formData['pagenow'] : 1;
        $limit = isset($formData['limit']) ? $formData['limit'] : 10;
        $dataList = $this
            ->alias("a")
            ->leftJoin("t_goods_type b", "a.goods_type_id=b.id")
            ->field($field)
            ->status(1)
            ->keyword($keyword)
            ->goodsType($goodsType)
            ->where('b.status', 0)
            ->where('a.goods_type_id', '<>',129)
            ->order('a.sort', 'desc')
            ->order('a.id', 'desc')
            ->paginate(['page' => $pagenow, 'list_rows' => $limit], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
        return $ret;
    }


    /**
     * 首页商品列表获取
     * @param $formData
     * @param string $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function goodsIndex($formData, $field = "a.store_id,a.goods_type_id,a.goods_title,a.goods_text,a.goods_img,a.goods_max_price,a.goods_min_price,a.goods_min_market_price,a.id as goods_id,b.name")
    {
        $goods_type_model = new GoodsTypeModel();
        $goods_type_list = $goods_type_model->where('status', 0)->field('id,name')->order('sort DESC')->limit(2)->select();
        $goods_type_ids = [];
        $goods_data = [];
        foreach ($goods_type_list as $value) {
            $goods_type_ids[] = $value['id'];
            $goods_data[intval($value['id'])]['store'] = $value;
            $goods_data[intval($value['id'])]['list'] = [];
        }
        $limit = isset($formData['limit']) ? $formData['limit'] : 10;
        $dataList = $this
            ->alias("a")
            ->leftJoin("t_goods_type b", "a.goods_type_id=b.id")
            ->field($field)
            ->status(1)
            ->whereIn('b.id', $goods_type_ids)
            ->where('b.status', 0)
            ->order('a.id', 'desc')
            ->order('a.sort', 'desc')
            ->paginate(['page' => 1, 'list_rows' => $limit], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $dataList = $dataList->items();
        foreach ($dataList as $value) {
            $goods_data[intval($value['goods_type_id'])]['list'][] = $value;
        }
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
        return $ret;
    }

    /**
     * 获取单条数据
     * @param $id
     * @param string $field
     * @param int $store_id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGoodsInfo($id, $field = '*', $store_id = 0)
    {
        $data = $this->alias("a")
            ->storeId($store_id)
            ->leftJoin("t_goods_type b", "a.goods_type_id=b.id")
            ->where('a.id', $id)
            ->field($field)
            ->find();
        if (empty($data)) {
            return $data;
        }
        $goods_common_model = new GoodsCommonModel();
        $goods_common_list = $goods_common_model->getCommonGoods($id);
        $attribute_ids = [];
        foreach ($goods_common_list as $value) {
            if (strpos($value['attribute_ids'], '_') > 0) {
                $attribute_ids_arr = explode('_', $value['attribute_ids']);
            } else {
                $attribute_ids_arr[] = $value['attribute_ids'];
            }
            $attribute_ids = array_merge($attribute_ids, $attribute_ids_arr);
        }
        $attribute_ids = array_unique($attribute_ids);
        $goods_attr_list = $goods_common_model->getAttrList($id, $attribute_ids);
        $data['goods_list'] = $goods_common_list;
        $data['attr_list'] = $goods_attr_list;
        return $data;
    }

    /**
     * 获取当前商品最近购买记录
     * @param $id
     * @param int $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\
     */
    public function getGoodsBuyLog($id, $limit = 6)
    {
        $goods_model = new GoodsBuyLogModel();
        $list = $goods_model->getListGroup(['goods_id' => $id], $limit);
        return $list->toArray();
    }

    /**
     * 商品添加/更新
     * @param $goods_data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addUpdateGoods($goods_data)
    {
        $goods_list = $goods_data['goods_list'];
        $attr_ids = $goods_data['attr_ids'];
        unset($goods_data['attr_ids']);
        unset($goods_data['goods_list']);
        unset($goods_data['attr_List']);
        if (!empty($goods_data['goods_parameter'])) {
            $goods_data['goods_parameter'] = json_encode($goods_data['goods_parameter']);
        }
        $data = $this->saveData($goods_data);
        if (false === $data['flag']) {
            return $data;
        }
        $goods_id = $data['id'];
        $goods_title = $goods_data['goods_title'];
        $goods_image = $goods_data['goods_img'];
        $store_id = $goods_data['store_id'];
        $goods_common_ids = [];
        foreach ($goods_list as &$value) {
            unset($value['number']);
            if (empty($value['id'])) {
                unset($value['id']);
            } else {
                $goods_common_ids[] = $value['id'];
            }
            $value['goods_id'] = $goods_id;
            $value['goods_title'] = $goods_title;
            if (empty($value['goods_image'])) {
                $value['goods_image'] = $goods_image;
            }
            $value['store_id'] = $store_id;
            $value['goods_agency_price'] = $value['goods_sell_price'];
        }
        $goods_common_model = new GoodsCommonModel();
        $goods_common_model->withTrashed()->where('goods_id', $goods_id)->whereNotIn('id', $goods_common_ids)->delete();
        $ret = $goods_common_model->saveAll($goods_list);
        GoodsAttributeModel::upAttrGoodsId($goods_id, $attr_ids);
        if (false !== $ret) {
            return $data;
        }
        return ['flag' => false, 'id' => 0];
    }

    /**
     * 改变库存
     * @param $id
     * @param $storage
     * $storage['storage']  改变的库存
     * $storage['attribute_ids']  商品属性id
     * $storage['target_id']  平台进货表示渠道商id  代理商时表示代理商id  活动时表示活动id  店铺id
     * @param $change
     * @param int $user_id 售卖时表示购买者id
     * @param array $operate
     * $operate['operate']  system平台商进货 agency代理商拿货 activity活动扣货  store商户库存管理
     * $operate['admin_id']  管理员id
     * @param string $remark 备注信息
     * @return mixed
     * @throws \Exception
     */
    public function changeStore($id, $storage, $change, $user_id = 0, $operate = [], $remark = "")
    {
        $goods_store_model = new GoodsStoreModel();
        $goods_common_model = new GoodsCommonModel();
        $map = [
            'goods_id' => $id,
            'attribute_ids' => $storage['attribute_ids']
        ];
        $goods_data = $goods_common_model->where($map)->field('goods_storage')->find();
        switch ($operate['operate']) {
            //平台进货/平台售卖商品
            case "system":
                $this->startTrans();
                if ($change == 'add') {
                    $goods_storage = intval($goods_data['storage']) + intval($goods_data['goods_storage']);
                    if (empty($remark)) {
                        $remark = "平台增加操作";
                    }
                } else {
                    if ((intval($goods_data['goods_storage']) - $storage['storage']) < 0) {
                        $this->rollback();
                        return false;
                    }
                    $goods_storage = intval($goods_data['goods_storage']) - $storage['storage'];
                    if (!empty($remark)) {
                        $remark = "平台减少操作";
                    }
                }
                $ret = $goods_common_model->changeStore($id, $storage['attribute_ids'], $goods_storage);
                if ($ret !== false) {
                    $in_data = [
                        'goods_id' => $id,
                        'attribute_ids' => $storage['attribute_ids'],
                        'storage' => $storage['storage'],
                        'target_id' => $storage['target_id'],
                        'last_storage' => $goods_data['goods_storage'],
                        'change' => $change,
                        'user_id' => $user_id,
                        'operate' => "system",
                        'admin_id' => $operate['admin_id'],
                        'remark' => $remark,
                        'add_time' => time()
                    ];
                    $ret = $goods_store_model->addStorage($in_data);
                    if ($ret !== false) {
                        $this->commit();
                        return true;
                    }
                }
                $this->rollback();
                break;
            case "agency":
                $this->startTrans();
                if ($change == 'add') {
                    if ((intval($goods_data['goods_storage']) - $storage['storage']) < 0) {
                        $this->rollback();
                        return false;
                    }
                    $goods_storage = intval($goods_data['goods_storage']) - $storage['storage'];
                    $change_sys = "sub";
                    if (empty($remark)) {
                        $remark = "给代理商发货";
                    }
                } else {
                    $goods_storage = $storage['storage'] + intval($goods_data['goods_storage']);
                    $change_sys = "add";
                    if (empty($remark)) {
                        $remark = "回购代理商货物";
                    }
                }
                $ret = $goods_common_model->changeStore($id, $storage['attribute_ids'], $goods_storage);
                if ($ret !== false) {
                    $in_data = [
                        'goods_id' => $id,
                        'attribute_ids' => $storage['attribute_ids'],
                        'storage' => $storage['storage'],
                        'target_id' => $storage['target_id'],
                        'last_storage' => $goods_data['goods_storage'],
                        'change' => $change_sys,
                        'user_id' => 0,
                        'operate' => "system",
                        'admin_id' => $operate['admin_id'],
                        'remark' => $remark,
                        'add_time' => time()
                    ];
                    $ret = $goods_store_model->addStorage($in_data);
                    if ($ret !== false) {
                        //修改代理商库存
                        $agency_goods_store_model = new AgencyGoodsModel();
                        $ret = $agency_goods_store_model->changeStore($in_data, $change);
                        if ($ret !== false) {
                            $this->commit();
                            return true;
                        }
                        $this->rollback();
                    }
                }
                $this->rollback();
                break;
            case "activity":
                $this->startTrans();
                if ($change == 'add') {
                    if ((intval($goods_data['goods_storage']) - $storage['storage']) < 0) {
                        $this->rollback();
                        return false;
                    }
                    $goods_storage = intval($goods_data['goods_storage']) - $storage['storage'];
                    $change_sys = "sub";
                    if (empty($remark)) {
                        $remark = "平台活动库存囤货";
                    }
                } else {
                    $goods_storage = $storage['storage'] + intval($goods_data['goods_storage']);
                    $change_sys = "add";
                    if (empty($remark)) {
                        $remark = "扣除活动库存囤货";
                    }
                }
                $ret = $goods_common_model->changeStore($id, $storage['attribute_ids'], $goods_storage);
                if ($ret !== false) {
                    $in_data = [
                        'goods_id' => $id,
                        'attribute_ids' => $storage['attribute_ids'],
                        'storage' => $storage['storage'],
                        'target_id' => $storage['target_id'],
                        'last_storage' => $goods_data['goods_storage'],
                        'change' => $change_sys,
                        'user_id' => 0,
                        'operate' => "system",
                        'admin_id' => $operate['admin_id'],
                        'remark' => $remark,
                        'add_time' => time()
                    ];
                    $ret = $goods_store_model->addStorage($in_data);
                    if ($ret !== false) {
                        $activity_goods_store_model = new ActivityGoodsModel();
                        $ret = $activity_goods_store_model->changeStore($in_data, $change);
                        if ($ret === true) {
                            $this->commit();
                            return true;
                        }
                    }
                }
                $this->rollback();
                break;
            case "store":
                $this->startTrans();
                if ($change == 'add') {
                    $goods_storage = $storage['storage'] + intval($goods_data['goods_storage']);
                    if (empty($remark)) {
                        $remark = "商家进货";
                    }
                } else {
                    if ((intval($goods_data['goods_storage']) - $storage['storage']) < 0) {
                        $this->rollback();
                        return false;
                    }
                    $goods_storage = intval($goods_data['goods_storage']) - $storage['storage'];
                    if (!empty($user_id)) {
                        $up_sale_data['goods_sale'] = intval($goods_data['goods_sale']) + $storage['storage'];
                        $this->where(['id' => $id])->update($up_sale_data);
                        $remark = "商品售卖";
                    }
                }
                $ret = $goods_common_model->changeStore($id, $storage['attribute_ids'], $goods_storage);
                if ($ret !== false) {
                    $in_data = [
                        'goods_id' => $id,
                        'attribute_ids' => $storage['attribute_ids'],
                        'storage' => $storage['storage'],
                        'last_storage' => $goods_data['goods_storage'],
                        'change' => $change,
                        'user_id' => $user_id,
                        'operate' => "store",
                        'admin_id' => $operate['admin_id'],
                        'remark' => $remark,
                        'add_time' => time()
                    ];
                    $ret = $goods_store_model->addStorage($in_data);
                    if ($ret !== false) {
                        $this->commit();
                        return true;
                    }
                }
                $this->rollback();
                break;
            default:
        }
        return false;
    }

    public function goodsShearch($formData, $user_id)
    {
        $keyword = $formData['keyword'];
        $pagenow = $formData['pagenow'];
        $GoodsModel = new GoodsModel();
        $UserCollectUpModel = new UserCollectUpModel();
        $goodsField = "id,goods_title,goods_text,goods_img,goods_photo,goods_detail,goods_up_count,goods_share_count,goods_collect_count,goods_read_count,goods_return_money,goods_top_money";
        //全部
        $data = $GoodsModel
            ->where("goods_status", 1)
            ->where("goods_title like '%" . $keyword . "%'")
            ->limit((($pagenow - 1) * 8), $pagenow * 8)
            ->order("sort desc,id desc")
            ->field($goodsField)
            ->select();

        foreach ($data as $key => $value) {
            //收藏点赞
            if (!empty($user_id)) {
                //登录
                $data[$key]['is_collect'] = ($UserCollectUpModel->getChildInfo($user_id, $value['id'], 1)) ? true : false;//收藏
                $data[$key]['is_up'] = ($UserCollectUpModel->getChildInfo($user_id, $value['id'], 2)) ? true : false;//点赞
            } else {
                //未登录
                $data[$key]['is_collect'] = false;
                $data[$key]['is_up'] = false;
            }
            //拼团
            $data[$key] = Util::goodsDataSwitch($data[$key]);//参数转换
        }
        return $data;
    }

    /**
     * 小程序商品详情
     * @param $goods_id
     * @param string $user_id
     * @param bool $is_bean
     * @return array|\think\Model|null
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDetail($goods_id, $user_id = '', $is_bean = false)
    {
        $goodsField = "id,store_id,goods_title,goods_text,goods_img,goods_photo,goods_detail,goods_tag,goods_special,goods_parameter,goods_max_price,
        goods_min_price,goods_up_count,goods_share_count,goods_collect_count,goods_read_count,goods_return_money,goods_top_money,goods_sale,goods_reserve,goods_reserve_storage,goods_reserve_send,goods_storage,send_remark,serve_remark,is_member";
        $data = $this->where("goods_status", 1)
            ->where("id", $goods_id)
            ->order("sort desc,id desc")
            ->field($goodsField)
            ->find();
        if (!isset($data['id'])) {
            throw new \think\Exception("商品不存在", 0);
        }
        //是否会员
        $data['popularize_code'] = "";
        $data['cart_num'] = 0;
        $data['is_permission'] = false;
        if (!empty($user_id)) {
            $member_level = UserModel::getIsMemberLevel($user_id);
            $UserModel = new UserModel();
            $user = $UserModel->getInfo($user_id, 'popularize_code');
            if (intval($member_level) >= $data['is_member']) {
                $data['is_permission'] = true;
            }
            $data['popularize_code'] = $user['popularize_code'];

            $UserCartModel = new UserCartModel();
            $data['cart_num'] = $UserCartModel->alias('a')
                ->leftJoin("t_goods g", "a.goods_id=g.id")
                ->leftJoin("t_goods_type b", "g.goods_type_id=b.id")
                ->leftJoin("t_goods_common c", "a.attribute_ids=c.attribute_ids")
                ->where("a.user_id", $user_id)
                ->where("a.type", 0)
                ->where('b.status', 0)
                ->where("g.delete_time", 0)
                ->where("g.goods_status", 1)
                ->where('a.goods_number', '>', 0)
                ->group('a.attribute_ids')->count();
        }
        if ($is_bean) {
            //判断是否是团购商品
        }
        $data = Util::goodsDataSwitch($data);//参数转换
        return $data;
    }

    /**
     * 更新转发次数
     * @param $goods_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function shareAdd($goods_id)
    {
        $sql = "UPDATE t_goods SET goods_share_count = goods_share_count + 1 WHERE id = {$goods_id}";
        $ret = Db::query($sql);
        if ($ret !== false) {
            return true;
        }
        return false;
    }

    /**
     * 更新阅读次数
     * @param $goods_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function readAdd($goods_id)
    {
        $sql = "UPDATE t_goods SET goods_read_count = goods_read_count + 1 WHERE id = {$goods_id}";
        $ret = Db::query($sql);
        if ($ret !== false) {
            return true;
        }
        return false;
    }

    /**
     * 生成商品推广图片
     * @param $goods_id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function createGeneralizeImg($goods_id)
    {
        $file_path = "./goods_img/generalize/";
        if (!is_dir($file_path)) {
            mkdir($file_path, 0777);
        }
        $poster = "./goods_img/poster_bac.jpg";
        $goods_data = $this->getInfo($goods_id, "goods_title,goods_img,goods_max_price,goods_min_price");
        if (empty($goods_data)) {
            return false;
        }
        $goods_original_price = $goods_data['goods_max_price'];
        $goods_bazaar_price = $goods_data['goods_min_price'];
        $image = Image::open($poster);
        $save_name = "./goods_img/generalize/" . $goods_id . ".png";//存储路径
        $goods_img = "./goods_img/generalize/" . $goods_id . "_original.png";
        $cj_goods_img = "./goods_img/generalize/" . $goods_id . "_cj.png";
        file_put_contents($goods_img, file_get_contents($goods_data['goods_img']));
        $font = getcwd() . '/msyh.ttf';//字体
        $i = 730;
        $title = $this->autowrap(30, 0, $font, $goods_data['goods_title'], $i);
        $image->text($title, $font, 30, '#27292a', 1, array(20, 160), 0, 730);//商品标题
        $image->text("优惠价:" . $goods_bazaar_price, $font, 38, '#db2828', 1, array(20, 280));//优惠价
        $image->text("原价:" . $goods_original_price, $font, 25, '#c2c2c2', 1, array(20, 345));//原价
        $goods_img = Image::open($goods_img);
        $goods_img->thumb(500, 540, 3)->save($cj_goods_img);
        $image->water($cj_goods_img, array((750 - 520) / 2, 400))->save($save_name);//商品图片
        $goods_img = "./goods_img/generalize/" . $goods_id . "_original.png";
        $cj_goods_img = "./goods_img/generalize/" . $goods_id . "_cj.png";
        if (file_exists($goods_img)) {
            unlink($goods_img);
        }
        if (file_exists($cj_goods_img)) {
            unlink($cj_goods_img);
        }
        return $save_name;
    }

    private function autowrap($fontsize, $angle, $fontface, $string, $width)
    {
        // 参数分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
        $content = "";
        // 将字符串拆分成一个个单字 保存到数组 letter 中
        preg_match_all("/./u", $string, $arr);
        $letter = $arr[0];
        foreach ($letter as $l) {
            $teststr = $content . $l;
            $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
            if (($testbox[2] > $width) && ($content !== "")) {
                $content .= PHP_EOL;
            }
            $content .= $l;
        }
        return $content;
    }

    /**
     * 判断是否有商品
     * @param $nav_id
     * @param int $is_member
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function isHasGoods($nav_id, $is_member = 1)
    {
        $map = [
            'a.goods_nav_id' => $nav_id,
            'a.goods_status' => 1,
            'c.status' => 0
        ];
        $goods_model = new GoodsModel();
        $goods = $goods_model
            ->alias('a')
            ->isMember($is_member)
            ->leftJoin("t_goods_type c", "a.goods_type_id=c.id")
            ->where($map)->find();
        if (empty($goods)) {
            return false;
        }
        return true;
    }

    /**
     * 判断商品限购
     * @param $goods_id
     * @param $user_id
     * @return float|int|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function isLimitNumber($goods_id, $user_id)
    {
        $goods_model = new GoodsModel();
        $goods_data = $goods_model->where(['id' => $goods_id])->field('limit_number')->find();
        $order_item_model = new OrderItemModel();
        $sum = $order_item_model->where(['user_id' => $user_id, 'goods_id' => $goods_id])->where('order_status', '>', 0)->sum('goods_number');
        if (empty($sum)) {
            $sum = 0;
        }
        $sum = $goods_data['limit_number'] - $sum;
        return $sum > 0 ? $sum : 0;
    }
}
